<template>
  <div class="home-bg">
    <div class="main-scroll" style="margin-top: -80px;" ref="mainScrollRef" @scroll="onMainScroll">
      <div class="main-cols">
        <div class="main-col" v-for="(group, colIdx) in groups" :key="group.title">
          <div class="group-title">{{ group.title }}</div>
          <div class="icon-scroll">
            <div class="icon-list">
              <div class="icon-item" @mousedown="e => handleDragStart(item, e)" @touchstart="e => handleTouchStart(item, e)" @mouseup="handleDragEnd" @mouseleave="handleDragEnd" @touchend="e => handleTouchEnd(item, e)" @click="handleItemClick(item, $event)" v-for="item in group.items" :key="item.name">
                <img :src="getImageUrl(item)" class="icon-img" />
                 <!-- <img src="../../assets/image/heardimg.png" alt="" class="icon-img"> -->
                <div class="icon-label" style="font-size: 13px;">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="custom-pagination">
      <span v-for="i in 4" :key="i" :class="['dot', getDotClass(i-1)]"></span>
    </div>


    <ConfigSetting ref="configSettingRef" />
    <SetConfig ref="setConfigRef" @onOk="onOk" />
  </div>
</template>
<script setup lang="ts">
import { ElLoading } from 'element-plus'
import { onMounted, onUnmounted, ref } from 'vue'

// import ConfigSetting from '../../components/ConfigSetting.vue'
import { useRouter } from 'vue-router'
import { BaseUrl } from '../../utils/request'
import SetConfig from './components/SetConfig.vue'

// 翻译系统
const translationVersion = ref(0)
let t = (key: any, params?: any) => {
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../i18n/locales/en-US')
		} else {
			langModule = await import('../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationVersion.value++
	} catch (error) {
		console.error('Failed to load translations:', error)
	}
}

const router = useRouter()
const configSettingRef = ref<any>(null)
const setConfigRef = ref<any>(null)
const mainScrollRef = ref()
const activePage = ref(0)
const indexData = ref<any>(null)

// 图片URL缓存
const imageUrlCache = new Map<string, string>()

const groups :any= ref([
  {
    title: t('pages.home.assessmentScale'),
    items: [
      
    ]
  },
  {
    title: t('pages.home.cognitiveTraining'),
    items: [
   
    ]
  },
  {
    title: t('pages.home.handEyeCoordination'),
    items: [
    
    ]
  },
  {
    title: t('pages.home.groupFour'),
    items: []
  },
 
])

// 更新组标题的函数
function updateGroupTitles() {
  groups.value[0].title = t('pages.home.assessmentScale')
  groups.value[1].title = t('pages.home.cognitiveTraining')
  groups.value[2].title = t('pages.home.handEyeCoordination')
  groups.value[3].title = t('pages.home.groupFour')
}

function onOk(item: any) {
  console.log(item);
  let user = JSON.parse(localStorage.getItem('user') || '{}')
  let taskId: any = localStorage.getItem('taskId') 
  if (!taskId) {
        taskId = {
          id: ''
        }
      } else {
        taskId = JSON.parse(taskId)
  }
      let resource = localStorage.getItem('resource')
      //开始任务
      window.request?.('/task/actionTask', { method: 'POST', body: {
        id: item.id,
        // taskId: taskId.id,
        // executionNumber:taskId.executionNumber,
        patientId: user.id,
        resource: 1,
        action:1,
        linkId: item.id,
        linkName:item.name,

        type:1
      } })
  
}
const setConfig = (item: any) => {
  if (item.config) {
    setConfigRef.value.show(item)

  } else { 
    
    const loading = ElLoading.service({
      lock: false,
    text: t('pages.home.loading'),
    background: 'rgba(0, 0, 0, 0.7)',
  })
    //获取配置
    window.request?.('/system/scale/'+item.id, { method: 'GET' }).then(res => {
      console.log(res);
      console.log(JSON.parse(res.content));
      localStorage.setItem('gameName', res.name)
      localStorage.setItem('scaleId', res.id)
      localStorage.setItem('scaleConfig', res.content)
      let user = JSON.parse(localStorage.getItem('user') || '{}')
      let taskId: any = localStorage.getItem('taskId') 
      console.log(taskId);
      if (!taskId) {
        taskId = {
          id: ''
        }
      } else {
        taskId = JSON.parse(taskId)
      }
     router.push('/game')
      let resource = localStorage.getItem('resource')
      window.request?.('/task/actionTask', { method: 'POST', body: {
        id: item.id,
        // taskId: taskId.id||'',
        // executionNumber:taskId.executionNumber,
        patientId: user.id,
        resource: 1,
        action:1,
        linkId: item.id,
        type: 2,
        linkName:res.name
      } })
      loading.close()
    }).catch(err => { 
      console.log(err);
      
      loading.close()
      window.messageRef?.show(err.message, 'error')
    })
  }
}
function getRows(items: any[]) {
  // 每行6个，分成4行
  const rows = []
  for (let i = 0; i < 4; i++) {
    rows.push(items.slice(i * 6, (i + 1) * 6))
  }
  return rows
}

function enableDragScroll() {
  const el = mainScrollRef.value
  if (!el) return
  
  // 鼠标拖拽滑动
  let isDown = false
  let startX = 0
  let scrollLeft = 0
  
  el.addEventListener('mousedown', (e: MouseEvent) => {
    if (isDragging) return
    isDown = true
    startX = e.pageX - el.offsetLeft
    scrollLeft = el.scrollLeft
    el.classList.add('dragging')
  })
  
  el.addEventListener('mouseleave', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  
  el.addEventListener('mouseup', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  
  el.addEventListener('mousemove', (e: MouseEvent) => {
    if (!isDown || isDragging) return
    e.preventDefault()
    const x = e.pageX - el.offsetLeft
    const walk = (x - startX)
    el.scrollLeft = scrollLeft - walk
  })

  // 触屏水平滑动支持
  let isTouching = false
  let touchStartX = 0
  let touchStartY = 0
  let touchScrollLeft = 0
  let touchStartTime = 0
  let isHorizontalSwipe = false
  
  el.addEventListener('touchstart', (e: TouchEvent) => {
    if (isDragging || e.touches.length !== 1) return
    isTouching = true
    touchStartX = e.touches[0].clientX
    touchStartY = e.touches[0].clientY
    touchScrollLeft = el.scrollLeft
    touchStartTime = Date.now()
    isHorizontalSwipe = false
  }, { passive: true })
  
  el.addEventListener('touchmove', (e: TouchEvent) => {
    if (!isTouching || isDragging || e.touches.length !== 1) return
    
    const touchX = e.touches[0].clientX
    const touchY = e.touches[0].clientY
    const deltaX = Math.abs(touchX - touchStartX)
    const deltaY = Math.abs(touchY - touchStartY)
    
    // 判断是否为水平滑动
    if (!isHorizontalSwipe && (deltaX > 10 || deltaY > 10)) {
      isHorizontalSwipe = deltaX > deltaY * 1.5 // 水平滑动阈值
    }
    
    // 如果是水平滑动，处理滚动
    if (isHorizontalSwipe && deltaX > 5) {
      const walk = touchStartX - touchX
      el.scrollLeft = touchScrollLeft + walk
      e.preventDefault() // 阻止垂直滚动
    }
  }, { passive: false })
  
  el.addEventListener('touchend', () => {
    isTouching = false
    isHorizontalSwipe = false
  }, { passive: true })
}

// 为 icon-scroll 增加触屏上下滑动支持
function enableIconScrollTouch() {
  const iconScrolls = document.querySelectorAll('.icon-scroll')
  iconScrolls.forEach(dom => {
    const el = dom as HTMLElement
    let isTouching = false
    let startY = 0
    let scrollTop = 0
    let startTime = 0
    
    // 支持 PC 触摸屏
    el.addEventListener('touchstart', function (e) {
      const te = e as TouchEvent
      if (te.touches.length !== 1) return
      isTouching = true
      startY = te.touches[0].pageY - el.offsetTop
      scrollTop = el.scrollTop
      startTime = Date.now()
      // 不阻止默认行为，让父容器也能响应
    }, { passive: true })
    
    el.addEventListener('touchmove', function (e) {
      if (!isTouching || isDragging) return
      const te = e as TouchEvent
      if (te.touches.length !== 1) return
      
      const y = te.touches[0].pageY - el.offsetTop
      const walkY = y - startY
      const newScrollTop = scrollTop - walkY
      
      // 只有当确实需要滚动时才阻止默认行为
      if ((newScrollTop > 0 && newScrollTop < el.scrollHeight - el.clientHeight) ||
          (walkY < 0 && el.scrollTop > 0) ||
          (walkY > 0 && el.scrollTop < el.scrollHeight - el.clientHeight)) {
        el.scrollTop = newScrollTop
        te.preventDefault()
      }
      // 否则让事件冒泡到父容器处理水平滑动
    }, { passive: false })
    
    el.addEventListener('touchend', function () {
      isTouching = false
    })
  })
}

function onMainScroll(e: Event) {
  const el = e.target as HTMLElement
  const scroll = el.scrollLeft
  const max = el.scrollWidth - el.clientWidth
  const percent = max === 0 ? 0 : scroll / max
  // 分4页，0~0.25, 0.25~0.5, 0.5~0.75, 0.75~1
  if (percent >= 0.75) {
    activePage.value = 3
  } else if (percent >= 0.5) {
    activePage.value = 2
  } else if (percent >= 0.25) {
    activePage.value = 1
  } else {
    activePage.value = 0
  }
}

function getDotClass(idx: number) {
  // 最左侧时前三个点全白
  if (activePage.value === 0) {
    return idx <= 2 ? 'active' : ''
  }
  // 最右侧时后三个点全白
  if (activePage.value === 3) {
    return idx >= 1 ? 'active' : ''
  }
  // 其它情况只高亮当前点
  return idx === activePage.value ? 'active' : ''
}

function getIndexData(forceRefresh = false) {
  // 清除缓存
  sessionStorage.removeItem('indexData')
  sessionStorage.removeItem('indexDataTimestamp')
  imageUrlCache.clear()
  console.log('清除缓存，请求新的首页数据')
  
  // 请求新数据
  console.log('请求新的首页数据')
  window.request?.('/system/index/getIndex', { method: 'GET' }).then(res => {
    indexData.value = res
    console.log(res);
    groups.value[0].items = res.scales
    groups.value[1].items = res.games[1]
    groups.value[2].items = res.games[2]
    groups.value[3].items = res.games[3]
  }).catch(err => {
    console.error('获取首页数据失败:', err)
  })
}

// 提供手动刷新数据的方法
function refreshIndexData() {
  console.log('手动刷新首页数据')
  // 清除图片URL缓存
  imageUrlCache.clear()
  getIndexData()
}

// 图片URL生成函数，优化缓存策略
function getImageUrl(item: any) {
  if (!item.cover) {
    return '../../assets/image/heardimg.png'
  }
  
  // 生成缓存键
  const cacheKey = `${item.id}_${item.cover}`
  
  // 检查内存缓存
  if (imageUrlCache.has(cacheKey)) {
    return imageUrlCache.get(cacheKey)!
  }
  
  // 如果有版本号，使用版本号；否则使用缓存时间戳，避免每次都用 Date.now()
  let version = item.version
  if (!version) {
    // 使用缓存时间戳作为版本号，这样同一次会话中图片版本号是一致的
    const cacheTimestamp = sessionStorage.getItem('indexDataTimestamp')
    version = cacheTimestamp || Date.now()
  }
  
  const imageUrl = `${BaseUrl}${item.cover}?v=${version}`
  
  // 缓存URL
  imageUrlCache.set(cacheKey, imageUrl)
  
  return imageUrl
}

// 拖拽相关
let dragTimer: any = null
let isDragging = false
let dragItem: any = null
let dragImage: HTMLElement | null = null
let dragSourceElement: HTMLElement | null = null // 记录被拖拽的原始元素
let shouldPreventClick = false // 新增：标记是否应该阻止点击事件
let currentMouseMoveHandler: ((e: MouseEvent) => void) | null = null // 跟踪当前的鼠标移动检测器
let touchStartTime = 0 // 记录触屏开始时间
let touchMoved = false // 记录是否发生了触屏移动

// 修改后的点击处理函数
function handleItemClick(item: any, e: Event) {
  console.log('🖱️ 点击事件触发:', item.name, 'shouldPreventClick:', shouldPreventClick, 'isDragging:', isDragging, 'dragTimer:', !!dragTimer)
  
  // 高DPI显示器坐标修正
  if (e instanceof MouseEvent && window.devicePixelRatio > 1) {
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    console.log('📍 点击坐标修正:', {
      原始坐标: { x: e.clientX, y: e.clientY },
      元素边界: rect,
      相对坐标: { x, y },
      设备像素比: window.devicePixelRatio
    })
    
    // 如果点击位置偏离中心过多，可能是坐标偏差
    const centerX = rect.width / 2
    const centerY = rect.height / 2
    const offsetX = x - centerX
    const offsetY = y - centerY
    
    if (Math.abs(offsetX) > rect.width * 0.3) {
      console.log('⚠️ 检测到可能的坐标偏差，offsetX:', offsetX)
    }
  }
  
  // 只有在正在拖拽时才阻止点击，不阻止正常点击
  if (isDragging) {
    console.log('❌ 阻止点击事件执行 - 正在拖拽')
    e.preventDefault()
    e.stopPropagation()
    return
  }
  
  // 如果有拖拽定时器在运行，说明可能是长按，稍等一下
  if (dragTimer) {
    console.log('⏰ 有拖拽定时器运行，延迟处理点击')
    setTimeout(() => {
      if (!isDragging && !dragTimer) {
        console.log('✅ 延迟执行点击')
        setConfig(item)
      }
    }, 50)
    return
  }
  
  // 如果最近刚完成拖拽操作，也阻止点击
  if (shouldPreventClick) {
    console.log('❌ 阻止点击事件执行 - 刚完成拖拽')
    e.preventDefault()
    e.stopPropagation()
    return
  }
  
  console.log('✅ 执行正常点击')
  setConfig(item)
}

// 清理拖拽图片元素
function cleanupDragImage() {
  if (dragImage) {
    console.log('清理拖拽图片元素')
    try {
      if (dragImage.parentNode) {
        dragImage.parentNode.removeChild(dragImage)
      }
    } catch (e) {
      console.warn('清理拖拽图片时出错:', e)
    }
    dragImage = null
  }
  
  // 额外安全措施：清理所有可能遗留的拖拽图片
  const existingDragImages = document.querySelectorAll('.drag-image')
  existingDragImages.forEach(img => {
    try {
      if (img.parentNode) {
        img.parentNode.removeChild(img)
        console.log('清理遗留的拖拽图片')
      }
    } catch (e) {
      console.warn('清理遗留拖拽图片时出错:', e)
    }
  })
  
  console.log('拖拽图片清理完成，剩余数量:', document.querySelectorAll('.drag-image').length)
}
function handleDragStart(item: any, e: MouseEvent | TouchEvent) {
  console.log('🎯 handleDragStart 触发:', e.type, '项目:', item.name)
  
  // 如果已经在拖拽或已有定时器，忽略
  if (isDragging || dragTimer) {
    console.log('⚠️ 已在拖拽或有定时器，忽略此次触发')
    return
  }
  
  // 记录被拖拽的原始元素和初始位置
  dragSourceElement = e.target as HTMLElement
  let startClientX = 0, startClientY = 0
  
  if (e instanceof MouseEvent) {
    startClientX = e.clientX
    startClientY = e.clientY
  } else if (e instanceof TouchEvent) {
    startClientX = e.touches[0].clientX
    startClientY = e.touches[0].clientY
  }
  
  // 阻止事件冒泡，避免干扰其他事件
  e.stopPropagation()
  
  if (e.type === 'mousedown') {
    console.log('🖱️ 鼠标按下，设置300ms定时器')
    dragTimer = setTimeout(() => {
      console.log('⏰ 鼠标长按时间到，开始拖拽')
      if (!isDragging) { // 双重检查
        startDrag(item, e as MouseEvent)
      }
    }, 300)
    
    // 添加鼠标移动检测，如果移动距离过大则取消长按
    const mouseMoveHandler = (moveEvent: MouseEvent) => {
      const deltaX = Math.abs(moveEvent.clientX - startClientX)
      const deltaY = Math.abs(moveEvent.clientY - startClientY)
      if (deltaX > 20 || deltaY > 20) { // 增加阈值到20px
        console.log('🖱️ 鼠标移动距离过大，取消长按拖拽')
        clearDragTimer()
      }
    }
    
    currentMouseMoveHandler = mouseMoveHandler
    document.addEventListener('mouseup', clearDragTimer)
    document.addEventListener('mousemove', mouseMoveHandler)
    document.addEventListener('mousemove', handleMouseMove)
  } else if (e.type === 'touchstart') {
    console.log('👆 触屏开始，设置300ms定时器')
    e.preventDefault() // 阻止默认行为，防止滚动等干扰
    dragTimer = setTimeout(() => {
      console.log('⏰ 触屏长按时间到，开始拖拽')
      if (!isDragging) { // 双重检查
        startDrag(item, e as TouchEvent)
      } else {
        console.log('❌ 触屏定时器触发时已在拖拽')
      }
    }, 300)
    document.addEventListener('touchend', clearDragTimer)
    document.addEventListener('touchmove', handleTouchMove, { passive: false })
    console.log('📝 触屏事件监听器已添加')
  }
}
function clearDragTimer() {
  console.log('清除拖拽定时器')
  clearTimeout(dragTimer)
  dragTimer = null
  document.removeEventListener('mouseup', clearDragTimer)
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('touchend', clearDragTimer)
  document.removeEventListener('touchmove', handleTouchMove)
  
  // 清理鼠标移动检测器
  if (currentMouseMoveHandler) {
    document.removeEventListener('mousemove', currentMouseMoveHandler)
    currentMouseMoveHandler = null
  }
  
  // 如果还没有开始拖拽但已经有拖拽图片，清理它
  if (!isDragging) {
    cleanupDragImage()
    // 清理原始元素样式
    if (dragSourceElement) {
      const iconItem = dragSourceElement.closest('.icon-item') as HTMLElement
      if (iconItem) {
        iconItem.classList.remove('dragging-source')
      }
      dragSourceElement = null
    }
    
    // 只在没有进入拖拽状态时，不设置点击阻止（这是正常的点击）
    console.log('✅ 正常点击，不阻止')
  } else {
    // 如果已经开始拖拽，短暂阻止点击事件
    shouldPreventClick = true
    setTimeout(() => {
      shouldPreventClick = false
      console.log('✅ 重置点击阻止标记')
    }, 50) // 缩短到50ms
  }
}
function startDrag(item: any, e: MouseEvent | TouchEvent) {
  console.log('🚀 开始拖拽:', item.name, '事件类型:', e.type)
  
  // 如果已经在拖拽，防止重复
  if (isDragging) {
    console.log('❌ 已经在拖拽中，忽略')
    return
  }
  
  // 清理之前可能存在的拖拽图片
  cleanupDragImage()
  
  isDragging = true
  dragItem = item
  console.log('✅ 设置 isDragging = true')
  
  // 给原始元素添加拖拽状态样式
  if (dragSourceElement) {
    const iconItem = dragSourceElement.closest('.icon-item') as HTMLElement
    if (iconItem) {
      iconItem.classList.add('dragging-source')
      console.log('🎨 给原始元素添加拖拽样式')
    }
  }
  
  // 只有触屏事件才创建拖拽图片，鼠标拖拽不显示
  if (e instanceof TouchEvent) {
    console.log('🖼️ 触屏拖拽：创建拖拽图片元素')
    dragImage = document.createElement('div')
    dragImage.className = 'drag-image'
    
    // 创建图片元素
    const img = document.createElement('img')
    img.src = BaseUrl + item.cover || '../../assets/image/heardimg.png'
    img.style.width = '64px'
    img.style.height = '64px'
    img.style.borderRadius = '16px'
    img.style.objectFit = 'cover'
    img.style.display = 'block'
    
    dragImage.appendChild(img)
    
    // 设置拖拽容器样式 - 使其看起来明显是预览
    dragImage.style.position = 'fixed'
    dragImage.style.pointerEvents = 'none'
    dragImage.style.zIndex = '10000'
    dragImage.style.background = '#fff'
    dragImage.style.border = '3px solid #ff6b35'  // 明显的橙色边框
    dragImage.style.padding = '4px'
    dragImage.style.borderRadius = '20px'
    dragImage.style.boxShadow = '0 8px 24px rgba(255, 107, 53, 0.4)'  // 橙色阴影
    dragImage.style.opacity = '0.95'
    dragImage.style.transform = 'translate(-50%, -50%) scale(1.1)'  // 稍微放大
    
    // 初始位置设为屏幕外，避免闪烁
    dragImage.style.left = '-1000px'
    dragImage.style.top = '-1000px'
    
    document.body.appendChild(dragImage)
    console.log('✅ 拖拽图片元素已添加到DOM，元素个数:', document.querySelectorAll('.drag-image').length)
    
    // 立即设置正确位置
    console.log('📍 立即设置拖拽图片位置')
    moveDragImage(e)
  } else {
    console.log('🖱️ 鼠标拖拽：不创建拖拽图片')
    // 鼠标拖拽不创建图片，dragImage 保持为 null
  }
}
function moveDragImage(e: MouseEvent | TouchEvent) {
  if (!dragImage) {
    console.log('moveDragImage: dragImage 不存在')
    return
  }
  
  let x = 0, y = 0, offsetY = 0
  
  if (e instanceof MouseEvent) {
    x = e.clientX; y = e.clientY
    offsetY = 10 // 鼠标向上偏移80px
    console.log('🖱️ 鼠标拖拽位置:', { x, y, type: e.type })
  } else if (e instanceof TouchEvent) {
          if (e.touches && e.touches.length > 0) {
        x = e.touches[0].clientX; y = e.touches[0].clientY
        offsetY = 0 // 触屏不偏移，直接跟随手指
        console.log('👆 触屏拖拽位置:', { x, y, type: e.type, touchCount: e.touches.length })
    } else {
      console.log('❌ TouchEvent 但没有 touches:', e.type)
      return
    }
  }
  
  // 分别为鼠标和触屏设置不同的偏移
  const finalX = x
  const finalY = y + offsetY
  
  dragImage.style.left = finalX + 'px'
  dragImage.style.top = finalY + 'px'
  
  console.log('📍 拖拽图片设置位置:', { finalX, finalY, offsetY, eventType: e.type })
}
function handleMouseMove(e: MouseEvent) {
  if (isDragging) moveDragImage(e)
}
function handleTouchMove(e: TouchEvent) {
  console.log('📱 handleTouchMove 触发:', { 
    isDragging, 
    hasDragTimer: !!dragTimer,
    touchCount: e.touches.length,
    eventType: e.type
  })
  
  if (isDragging) {
    console.log('✅ 正在拖拽，调用 moveDragImage')
    moveDragImage(e)
    e.preventDefault() // 只在拖拽时阻止默认行为
  } else if (dragTimer) {
    // 如果有定时器但还没开始拖拽，检查移动距离决定是否取消
    console.log('🚫 触屏移动，清除长按定时器')
    clearDragTimer()
  }
  // 其他情况不阻止默认行为，让主容器处理滑动
}
function handleDragEnd(e: MouseEvent | TouchEvent) {
  console.log('拖拽结束:', e.type)
  clearDragTimer()
  if (isDragging) {
    // 判断是否在icon-xiangmuzhuanyi上
    const target = document.querySelector('.bag')

    console.log('查找目标区域:', target);
    
    let x = 0, y = 0
    if (e instanceof MouseEvent) {
      x = e.pageX; y = e.pageY
    } else if (e instanceof TouchEvent) {
      x = e.changedTouches[0].pageX; y = e.changedTouches[0].pageY
    }
    if (target) {
      const rect = target.getBoundingClientRect()
      if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
        // 拖拽到icon-xiangmuzhuanyi
        console.log('拖拽成功到目标区域:', dragItem);
        let type=1
        groups.value[0].items.forEach((item: any) => {
          if(item.name === dragItem.name){
            type = 2
            console.log(item);
            
          }
        })
      let taskId: any = localStorage.getItem('taskId')

        if (!taskId) {
        taskId = {
          id: ''
        }
      } else {
        taskId = JSON.parse(taskId)
        }
      let resource = localStorage.getItem('resource')
        // alert('拖拽到icon-xiangmuzhuanyi成功，记录元素：' + JSON.stringify(dragItem))
        let user = JSON.parse(localStorage.getItem('user') || '{}')
        window.request?.('/task/addPocketTask', { method: 'POST', body: {
          linkId: dragItem.id,
          taskId: taskId.id,
          executionNumber: taskId.executionNumber,
          linkName: dragItem.name,
          patientId: user.id,
          resource: resource,
          type:type
        } }).then(res => {
          console.log(res);
          window.messageRef?.show(t('pages.home.addSuccess'), 'success')
        window.dispatchEvent(new CustomEvent('bg-change', { detail: res }))
          
        })
      }
    }
    // 清理拖拽相关状态
    cleanupDragImage()
    
    // 移除原始元素的拖拽样式
    if (dragSourceElement) {
      const iconItem = dragSourceElement.closest('.icon-item') as HTMLElement
      if (iconItem) {
        iconItem.classList.remove('dragging-source')
        console.log('移除原始元素拖拽样式')
      }
      dragSourceElement = null
    }
    
    isDragging = false
    dragItem = null
    
    // 拖拽结束后短暂阻止点击事件
    shouldPreventClick = true
    setTimeout(() => {
      shouldPreventClick = false
      console.log('✅ 拖拽结束后重置点击阻止标记')
    }, 50) // 缩短到50ms
  }
}

// 专门的触屏开始处理函数
function handleTouchStart(item: any, e: TouchEvent) {
  console.log('👆 触屏开始:', item.name)
  touchStartTime = Date.now()
  touchMoved = false
  
  // 如果已经在拖拽，直接返回
  if (isDragging || dragTimer) {
    return
  }
  
  // 记录初始位置
  const touch = e.touches[0]
  const startX = touch.clientX
  const startY = touch.clientY
  
  let longPressTimer: any = null
  let touchMoveHandler: any = null
  let hasMoved = false
  
  // 添加触屏移动监听来检测是否移动
  touchMoveHandler = (moveEvent: TouchEvent) => {
    const currentTouch = moveEvent.touches[0]
    const deltaX = Math.abs(currentTouch.clientX - startX)
    const deltaY = Math.abs(currentTouch.clientY - startY)
    
    hasMoved = deltaX > 20 || deltaY > 20
    
    if (hasMoved && !isDragging) {
      touchMoved = true
      console.log('👆 触屏移动过多，取消长按检测')
      // 取消长按定时器
      if (longPressTimer) {
        clearTimeout(longPressTimer)
        longPressTimer = null
      }
    } else if (isDragging) {
      // 如果已经在拖拽，处理拖拽移动
      console.log('👆 拖拽中移动')
      handleTouchMove(moveEvent)
    }
  }
  
  document.addEventListener('touchmove', touchMoveHandler, { passive: false })
  
  // 在触屏结束时清理监听器
  const cleanup = () => {
    document.removeEventListener('touchmove', touchMoveHandler)
    document.removeEventListener('touchend', cleanup)
    if (longPressTimer) {
      clearTimeout(longPressTimer)
      longPressTimer = null
    }
  }
  document.addEventListener('touchend', cleanup, { once: true })
  
  // 长按检测 - 只有在没有移动时才启动拖拽
  longPressTimer = setTimeout(() => {
    if (!touchMoved && !hasMoved) {
      console.log('👆 触屏长按确认，开始拖拽')
      // 只在开始拖拽时才阻止默认行为
      e.preventDefault()
      
      // 直接调用 startDrag，避免通过 handleDragStart 的复杂逻辑
      dragSourceElement = e.target as HTMLElement
      startDrag(item, e)
      
      // 长按启动拖拽后，移除局部监听器，避免冲突
      document.removeEventListener('touchmove', touchMoveHandler)
      // 添加全局拖拽移动监听
      document.addEventListener('touchmove', handleTouchMove, { passive: false })
    }
    longPressTimer = null
  }, 500) // 保持500ms的长按时间
}

// 专门的触屏结束处理函数
function handleTouchEnd(item: any, e: TouchEvent) {
  console.log('👆 触屏结束:', item.name, 'isDragging:', isDragging)
  
  const touchDuration = Date.now() - touchStartTime
  
  // 如果正在拖拽，处理拖拽结束
  if (isDragging) {
    console.log('👆 结束拖拽')
    handleDragEnd(e)
    // 清理拖拽相关的事件监听器
    document.removeEventListener('touchmove', handleTouchMove)
    return
  }
  
  // 强制清理任何可能残留的拖拽图片
  cleanupDragImage()
  
  // 如果是短按且没有移动，执行点击
  if (touchDuration < 500 && !touchMoved) {
    console.log('👆 触屏短按，执行点击，持续时间:', touchDuration + 'ms')
    // 延迟一点执行，确保拖拽相关状态已清理
    setTimeout(() => {
      if (!isDragging && !shouldPreventClick) {
        console.log('✅ 触屏点击执行')
        setConfig(item)
      } else {
        console.log('❌ 触屏点击被阻止，isDragging:', isDragging, 'shouldPreventClick:', shouldPreventClick)
      }
    }, 10)
  } else {
    console.log('👆 触屏长按或移动，不执行点击，持续时间:', touchDuration + 'ms', '移动:', touchMoved)
  }
  
  // 重置状态
  touchMoved = false
  touchStartTime = 0
}

onMounted(async () => {
  // 初始化翻译
  await initTranslations()
  // 更新组标题
  updateGroupTitles()
  
  // 监听登录成功事件，清除图片缓存
  const handleLoginSuccess = () => {
    imageUrlCache.clear()
    console.log('登录成功，已清除图片缓存')
  }
  window.addEventListener('loginSuccess', handleLoginSuccess)
  
  // 保存事件处理器引用，用于清理
  ;(window as any).homeLoginSuccessHandler = handleLoginSuccess
  
  // 高DPI显示器检测和修正
  const devicePixelRatio = window.devicePixelRatio || 1
  console.log('=== 高DPI显示器检测 ===')
  console.log('设备像素比:', devicePixelRatio)
  console.log('屏幕分辨率:', screen.width + 'x' + screen.height)
  console.log('视窗尺寸:', window.innerWidth + 'x' + window.innerHeight)
  console.log('==================')
  
  // 如果是高DPI显示器，应用修正
  if (devicePixelRatio > 1) {
    console.log('🔧 检测到高DPI显示器，应用修正')
    
    // 计算修正偏移量
    let offsetX = 0
    if (screen.width >= 3840) {
      // 4K显示器
      offsetX = -4
    } else if (devicePixelRatio >= 2) {
      offsetX = -3
    } else if (devicePixelRatio >= 1.5) {
      offsetX = -2
    } else if (devicePixelRatio >= 1.25) {
      offsetX = -1
    }
    
    console.log('计算的偏移量:', offsetX + 'px')
    
    // 为高DPI显示器优化CSS
    const style = document.createElement('style')
    style.textContent = `
      .icon-item {
        position: relative !important;
        left: ${offsetX}px !important;
        transform: translateZ(0) scale(1.0001) !important;
        backface-visibility: hidden !important;
        perspective: 1000px !important;
      }
      .icon-img, .icon-label {
        transform: translateZ(0) !important;
      }
      /* 确保点击区域精确对齐 */
      .icon-item::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: -1;
      }
    `
    document.head.appendChild(style)
  }
  
  // 检测设备类型和触屏支持
  const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0
  console.log('=== 设备检测信息 ===')
  console.log('设备支持触屏:', isTouchDevice)
  console.log('最大触点数:', navigator.maxTouchPoints)
  console.log('ontouchstart 支持:', 'ontouchstart' in window)
  console.log('用户代理:', navigator.userAgent)
  console.log('==================')
  
  // 添加全局触屏事件监听来测试
  document.addEventListener('touchstart', (e) => {
    console.log('🌍 全局 touchstart 事件触发:', e.touches.length, '个触点')
  }, { passive: true })
  
  document.addEventListener('touchmove', (e) => {
    console.log('🌍 全局 touchmove 事件触发:', e.touches.length, '个触点', '是否在拖拽:', isDragging)
  }, { passive: true })
  
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
  }
  getIndexData()
  enableDragScroll()
  enableIconScrollTouch()
  //设置默认密码
  if(localStorage.getItem('systemPassword') === null){
    localStorage.setItem('systemPassword', '123456')
  }
})

onUnmounted(() => {
  clearDragTimer()
  cleanupDragImage()
  isDragging = false
  dragItem = null
  currentMouseMoveHandler = null
  shouldPreventClick = false
  touchStartTime = 0
  touchMoved = false
  
  // 清理事件监听器
  if ((window as any).homeLoginSuccessHandler) {
    window.removeEventListener('loginSuccess', (window as any).homeLoginSuccessHandler)
    delete (window as any).homeLoginSuccessHandler
  }
  // 清理图片缓存
  imageUrlCache.clear()
})
</script>

<style scoped>
.home-bg {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--theme-secondary);
}
.main-scroll {
  width: 95vw;
  height: 80vh;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
  border-radius: 24px;
  scrollbar-width: none;
  -ms-overflow-style: none;
  /* 明确允许水平滑动 */
  touch-action: pan-x;
}
.main-scroll::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}
.main-cols {
  display: flex;
  flex-direction: row;
  height: 100%;
}
.main-col {
/* width: 70vw; */
  flex: 1 0 30vw;
  margin: 0 32px;
  background: rgba(255,255,255,0.18);
  border-radius: 24px;
  padding: 24px 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 确保触屏事件可以传递到父容器 */
  touch-action: pan-x pan-y;
  pointer-events: auto;
}
.main-col:first-child {
  margin-left: 0;
}
.group-title {
  font-size: 24px;
  color: #fff;
  margin-bottom: 18px;
  text-align: center;
  font-weight: bold;
  letter-spacing: 2px;
}
.icon-scroll {
  width: 100%;
  overflow-x: auto;
  overflow-y: auto;
  max-height: 68vh;
  scrollbar-width: none;
  -ms-overflow-style: none;
  /* 允许垂直滚动，但不阻止父容器的水平滑动 */
  touch-action: pan-y;
}
.icon-scroll::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}
.icon-list {
  display: flex;
  flex-wrap: wrap;
  gap: 24px 32px;
  justify-content: flex-start;
  align-items: flex-start;
  padding-left: 25px;
}
.icon-item {
  width: 140px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  touch-action: manipulation;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
  /* 优化高DPI显示器下的点击精度 */
  position: relative;
  z-index: 1;
  /* 增加点击区域的内边距 */
  padding: 8px;
  margin: -8px;
  /* 确保边界清晰 */
  box-sizing: border-box;
  /* 优化渲染性能 */
  will-change: transform;
  /* 防止子像素渲染问题 */
  transform: translateZ(0);
  /* 高DPI显示器修复 */
  image-rendering: crisp-edges;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* 强制使用整数像素 */
  contain: layout style paint;
  /* 允许父容器处理水平滑动 */
  pointer-events: auto;
}
.icon-img {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  background: #fff;
  margin-bottom: 8px;
  object-fit: cover;
}
.icon-label {
  font-size: 15px;
  text-align: center;
  width: 130px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #fff;
}
.main-scroll.dragging {
  cursor: grabbing;
  user-select: none;
}
.custom-pagination {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 98px;
  display: flex;
  justify-content: center;
  gap: 25px;
  z-index: 10;
}
.dot {
  width: 30px;
  height: 8px;
  border-radius: 8px;
  background: rgba(255,255,255,0.4);
  display: inline-block;
  transition: background 0.2s;
}
.dot.active {
  background: #fff;
}

/* 拖拽图片样式 */
.drag-image {
  position: fixed !important;
  pointer-events: none !important;
  z-index: 10000 !important;
  transition: none !important;
  /* transform 在 JS 中设置，避免这里的样式被覆盖 */
}

/* 正在被拖拽的原始元素样式 */
.icon-item.dragging-source {
  opacity: 0.5 !important;
  transform: translateZ(0) scale(0.9) !important;
  filter: grayscale(0.5) !important;
  transition: all 0.2s ease !important;
  /* 确保在拖拽时仍保持正确的层级 */
  z-index: 2 !important;
}

/* 高DPI显示器修正 */
@media (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
  .icon-item {
    transform: translateZ(0) scale(1.0001) !important;
    backface-visibility: hidden;
  }
}

@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
  .icon-item {
    position: relative;
    left: -1px;
    transform: translateZ(0) scale(1.0001) !important;
  }
}

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .icon-item {
    position: relative;
    left: -2px;
    transform: translateZ(0) scale(1.0001) !important;
  }
}

/* 针对4K显示器的特殊修正 */
@media screen and (min-width: 3840px) {
  .icon-item {
    position: relative;
    left: -3px;
    transform: translateZ(0) scale(1.0001) !important;
    backface-visibility: hidden;
    perspective: 1000px;
  }
  
  .icon-img, .icon-label {
    transform: translateZ(0) !important;
  }
}
</style>